const events = require('events');
const fs = require('fs');
var net = require("net");

var server = net.createServer(function (socket) {
    /* 获取地址信息 */
    var address = server.address();
    var message = "the server address is" + JSON.stringify(address);

    /* 发送数据 */
    socket.write(message, function () {
        var writeSize = socket.bytesWritten;
        console.log(message + "has send");
        console.log("the size of message is" + writeSize);
    })

    /* 监听data事件 */
    socket.on('data', function (data) {
        console.log(data.toString());
        var readSize = socket.bytesRead;
        console.log("the size of data is " + readSize);
    })
})

/* 获取地址信息 */
server.listen(8000, function () {
    console.log("Creat server on http://127.0.0.1:8000/");
})


/* 设置监听端口 */
// server.listen(8888);
// console.log("Creat server on http://127.0.0.1:8888/");
console.log(server);

/* 监听 connection 事件 */
server.on("connection", function (socket) {
    console.log("someone connects");
});

/* 设置监听时的回调函数 */
server.on("listening", function () {
    console.log("Creat server on http://127.0.0.1:8000/");
})

/* 设置关闭时的回调函数 */
server.on("close", function () {
    console.log("server closed!");
})

/* 设置错误时的回调函数 */
server.on("error", function (err) {
    console.log("error!");
})